//
//  LCHtmlController.m
//  wan77
//
//  Created by jiukuyinyue on 2017/8/25.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCYaoQingHtmlVC.h"
#import "LCViewController+YQShare.h"
#define scriptNameArr @[@"share",@"Copy"]

@interface LCYaoQingHtmlVC () 

@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, assign) CGFloat delayTime;

@end

@implementation LCYaoQingHtmlVC


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    for (NSInteger i = 0; i < scriptNameArr.count; i++) {
        [self.webView.configuration.userContentController addScriptMessageHandler:self name:scriptNameArr[i]];
    }
    #pragma mark -  禁止弹出键盘 注册通知
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    for (NSInteger i = 0; i < scriptNameArr.count; i++) {
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:scriptNameArr[i]];
    }
    #pragma mark -  禁止弹出键盘 卸载通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
- (void)dealloc {
    NSLog(@"__func__dealloc = %s", __func__);
    @try {
        [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    } @catch (NSException *exception) {}
    _webView.UIDelegate = nil;
    _webView.navigationDelegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.isNewAlert) {
        NSLog(@"isNewAlert = ");
    }
    _link = [NSString stringWithFormat:@"http://fuyin.app.inping.com/user/inv_family?usercode=%@",[_UserM usercode]];
    NSLog(@"调转链接 %@",_link);
    [self setupWebView];
    [self setupProgressView];
}


#pragma mark -  禁止弹出键盘
- (void)keyboardWillShow:(NSNotification *)aNotification {
    [self.view endEditing:YES];
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}
#pragma mark -
-(void)setupWebView{
    // 根据生成的WKUserScript对象，初始化WKWebViewConfiguration
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@"var e=document.getElementById('incode');e.onclick = function () { window.webkit.messageHandlers.Copy.postMessage(e.value);}"];
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [config.userContentController addUserScript:userScript];

    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) configuration:config];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _webView.frame = [self defaultSystemFrameWithIsNAVIGATION_BAR:YES];
    _webView.allowsBackForwardNavigationGestures = YES;//是否允许左右划手势导航,默认不允许
    
    [self.view addSubview:_webView];
    _webView.scrollView.bounces = NO;//禁止WebView滚动和回弹方法
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_link]];//goURLStrings[index]]];//创建URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url];//创建NSURLRequest
    [_webView loadRequest:request];//加载
}
- (CGRect)defaultSystemFrameWithIsNAVIGATION_BAR:(BOOL)isNAVIGATION_BAR {
    if (iPhoneX) {
        return CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, ScreenHeight - NAVIGATION_BAR_HEIGHT-15);
    }else{
        return CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, ScreenHeight - NAVIGATION_BAR_HEIGHT);
    }
}
- (void)setupProgressView
{
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 1, ScreenWidth, 2)];
    [self.view addSubview:_progressView];
    _progressView.progressTintColor = [UIColor redColor];//RGBColor(58, 150, 246)
    _progressView.trackTintColor = [UIColor clearColor];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {

        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        
        if (self.webView.estimatedProgress < 1.0) {
            self.delayTime = 1 - self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = 0;
        });

    } else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    }
}


- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"message.name = %@ message.body = %@", message.name,message.body);
    @try {
        if([message.name isEqualToString:@"share"]) {
            if ([message.body intValue] == 1) {
                [self ZKKShareViewDidSelecteBtnWithBtnText:@"分享朋友圈"];
            }
            if ([message.body intValue] == 2) {
                [self ZKKShareViewDidSelecteBtnWithBtnText:@"分享微信"];
            }
            if ([message.body intValue] == 3) {
                [self ZKKShareViewDidSelecteBtnWithBtnText:@"分享QQ"];
            }
            if ([message.body intValue] == 4) {
                [self ZKKShareViewDidSelecteBtnWithBtnText:@"QQ空间邀请"];
            }
            if ([message.body intValue] == 5) {
                [self ZKKShareViewDidSelecteBtnWithBtnText:@"微博邀请"];
            }
            if ([message.body intValue] == 6) {
                LSZQrCodeViewController * VC= [[LSZQrCodeViewController alloc]init];
                [self.navigationController pushViewController:VC animated:YES];
            }
            if ([message.body intValue] == 7) {
                [self ZKKShareViewDidSelecteBtnWithBtnText:@"更多邀请"];
            }
            
        }
        if([message.name isEqualToString:@"Copy"]) {
            NSLog(@"Copy message.body = %@", message.body);
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = message.body;
        }
    } @catch (NSException *exception) {
    }
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
}

/**
 *  在发送请求之前，决定是否跳转
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
     // 允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}


//加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.title = self.webView.title;
    NSMutableString *JSString = [NSMutableString string];
    // 拼接移除隐藏掉评论的JS代码
//    [JSString appendString:@"var bottomTag = document.getElementsByClassName('header')[0];bottomTag.parentNode.removeChild(bottomTag);"];
//        if (_isJumpCommentDiv) {
//            [JSString appendString:[NSString stringWithFormat:@"location.href='#comment';"]];//,self.webView.URL
//            _isJumpCommentDiv = NO;
//        }
    // 直接调用JS注入的方法即可
    [webView evaluateJavaScript:JSString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"result = %@", result);
    }];

}

// 提示框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示框" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}


@end
